package com.song.config.validation;

import com.song.annotation.EnumValidate;
import com.song.enums.BaseEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

public class EnumValidator implements ConstraintValidator<EnumValidate, Object> {
    private String[] enums;
    private Class<? extends BaseEnum<?>> baseEnum;

    @Override
    public void initialize(EnumValidate constraintAnnotation) {
        enums = constraintAnnotation.enums();
        baseEnum = constraintAnnotation.baseEnum();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        if (Objects.nonNull(baseEnum)){
            BaseEnum<?>[] enumConstants = baseEnum.getEnumConstants();
            for (BaseEnum<?> enumConstant : enumConstants) {
                if (Objects.equals(String.valueOf(enumConstant.getCode()), String.valueOf(o))){
                    return true;
                }
            }
            return false;
        }
        if (this.enums == null || this.enums.length == 0){
            return true;
        }
        for (String enumVal : enums) {
            if (Objects.equals(enumVal, String.valueOf(o))){
                return true;
            }
        }
        return false;
    }
}
